package ru.len.cafe.ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ru.len.cafe.entity.model.CafeTable;
import ru.len.cafe.entity.model.CafeTableStatusType;

/**
 * @author Stanislav Chetvertkov
 */

@Stateless
public class TableDao {

    @PersistenceContext(unitName="LenCafePU")
    private EntityManager em;
    
    /**
     * Add table to the database
     * @param table
     */
    public void createTable(CafeTable table){
	em.persist(table);
    }
    
    /**
     * Deletes table from the database
     * @param table
     */
    public void deleteTable(CafeTable table){
	em.remove(table);
    }
    
    /**
     * Updates existing table
     * @param table
     */
    public void updateTable(CafeTable table){
	em.refresh(table);
    }
    
    /**
     * Method returns list of tables
     * @param type. If not specified(null) then all tables would be selected 
     * @return Returns list of tables. If type is specified as 
     * BUSY then only busy tables would be selected, same thing with FREE and RESERVED.
     * 
     */
    @SuppressWarnings("unchecked")
    public List<CafeTable> selectTables(CafeTableStatusType type){			
	String jpql;
	if (type==null){
	    jpql = "SELECT t FROM CafeTable t";
	}else{
	    jpql = "SELECT t FROM CafeTable t WHERE t.cafeTaableStatusType = " + type.toString();	
	}
	
	Query query = em.createQuery(jpql);
	List<CafeTable> tables =(List<CafeTable>) query.getResultList();
	return tables;		
    }
    
}
